<template>
  <div class="spaceHome_box">
    <div class="spaceHome_box_left">
      <spaceContentLeft
      :space_name="spaceData.space_name"
      :spaceId="spaceData.space_id"
      :essay_list="essay_list"
      ></spaceContentLeft>
    </div>
    <div class="spaceHome_box_right">
      <div class="spaceHome_box_right_content">
        <n-scrollbar style="max-height: calc(100vh - 120px)">
          <spaceContentRight :spaceData="spaceData" :avatar="avatar"></spaceContentRight>
        </n-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import {spaceDateType} from "../../types"
import spaceContentRight from "../../components/spaceContentRight.vue"
import spaceContentLeft from "../../components/spaceContentLeft.vue";
import {getOneSpace} from "../../api/space"
import {GetUserMess} from "../../api/user"
import {getSpaceEssay} from "../../api/essay"
import { onMounted, ref,Ref, watch } from 'vue';
import {useStore} from "../../store/index"
import { useRouter } from 'vue-router';
const router = useRouter()
const store = useStore()

const avatar = ref("")
const spaceData:Ref<spaceDateType> = ref(
  {
    space_id: 0,
    space_name: "",
    space_image: "",
    username: "",
    create_day: "",
    space_people: "",
    space_essay_count: "",
    space_description: "",
    space_light_description: "",
    space_light_image: []
  },
)

const essay_list = ref([])

// 获取空间信息
const getSpace = async(spaceId:string) => {
  const space_data = await getOneSpace(Number(spaceId))
  if(space_data.code != "200"){
    window.$message.warning(space_data.message)
  }else{
    spaceData.value = space_data.data
    getUser()
  }
}

const getUser = async() => {
  const user_res = await GetUserMess(spaceData.value.phone as string)
  if(user_res.code!="200"){
    window.$message.warning(user_res.message)
  }else{
    avatar.value = user_res.data.avatar
  }
}

// 获取空间文章
const getEssay = async(spaceId:string) => {
  const essay_data = await getSpaceEssay(Number.parseInt(spaceId))
  if(essay_data.code!="200"){
    window.$message.warning(essay_data.message)
  }else{
    essay_list.value = essay_data.data.essayList
    store.setEssayList(essay_data.data.essayList)
  }
}

onMounted(async() => {
  
})

const checkCurrentRoute = (spaceId:string) => {
  getSpace(spaceId)
  getEssay(spaceId)
}

// 监听路由变化
watch(() => router.currentRoute.value.params.spaceId, (spaceId) => {
  checkCurrentRoute(spaceId as string)
},{ immediate: true, deep: true })

// 监听搜索结果变化
watch(() => store.searchEssayResult,
  (searchEssayResult) => {
    essay_list.value = searchEssayResult
  },
  { deep: true }
)
  
</script>

<style lang='scss' scoped>
  .spaceHome_box{
    position: relative;
    display: flex;
    
    .spaceHome_box_left{
      flex: 2;
    }
    .spaceHome_box_right{
      width: 300px;
      // flex: 1;

      .spaceHome_box_right_content{
        position: fixed;
      }
    }
  }
</style>